// 云函数入口文件
const cloud = require('wx-server-sdk')
const rq = require('request-promise');

cloud.init();
const db = cloud.database();
const playlistCollection = db.collection('yun-playlist');
const URL = 'http://musicapi.xiecheng.live/personalized';
const MAX_LIMIT = 100;

exports.main = async(event, context) => {

  // 获取总数量
  const countResult = await playlistCollection.count();
  const total = countResult.total;
  const batchTimes = Math.ceil(total / MAX_LIMIT);

  // 设置 promise 数组
  let tasks = [];
  for (let i = 0; i < batchTimes; i++) {
    let promise = await playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get();
    tasks.push(promise);
  }

  // 获取云数据库数据
  let list = {
    data: []
  };
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data)
      };
    });
  }

  // 获取 URL 数据
  let playlist = await rp(URL).then((res) => {
    return JSON.parse(res).result;
  });

  // 数组去重（云数据库数据与 URL 数据去重）
  let newData = [];
  for (let i = 0; i < playlist.length; i++) {
    let flag = true;
    for (let j = 0; j < list.data.length; i++) {
      if (playlist[i].id == list.data[i].id) {
        flag = false;
        break;
      }
    }
    if (flag) {
      newData.push(playlist[i]);
    }
  }

  // 装去重后的数据写入云数据库
  for (let i = 0; i < newData.length; i++) {
    await playlistCollection.add({
      data: {
        ...newData[i],
        createTime: db.serverDate()
      }
    }).then((res) => {
      console.log('插入数据');
    }).catch((err) => {
      console.log('插入失败');
    })
  }

  return newData.length;  

}